<script setup lang="ts">
import { nextTick, onMounted, reactive, ref, computed } from "vue";
import JinDrawer from "@/components/framework/jin-drawer/jin-drawer.vue";
import type { FormRule } from "@/types/commonType.ts";
import { FormInstance, Message } from "@arco-design/web-vue";
import useFormSubmit from "@/hooks/useFormSubmit.ts";
import {
  expertAddApi,
  expertEditApi,
  getTeacherList,
  getTeacherIds,
} from "@/services/expertGroup";
import type { ExpertGroupUpdateType } from "@/types/expertGroup";
import matchRules from "@/utils/Regexp";
const props = defineProps({
  title: String,
  dataType: Number,
});

const formRef = ref<FormInstance>();

const loading = ref(false);

const handleSubmit = useFormSubmit(formRef);

const emits = defineEmits<{
  (e: "list"): void;
}>();

const drawer = ref<{
  init: () => void;
  close: () => void;
}>();

const options = reactive({
  title: "",
  type: 0,
});

const formModel = reactive<ExpertGroupUpdateType>({
  groupName: "",
  teacherIds: "",
  groupId: "",
});

const rules = reactive<FormRule>({
  groupName: {
    required: true,
    message: "请输入专家组名称",
  },
  teacherIds: {
    required: true,
    message: "请选择专家",
  },
});

const handleCancel = () => {
  drawer.value?.close();
};

const promise = (url: any, msg: string) => {
  url
    .then((res: any) => {
      if (res.code === 200) {
        Message.success(msg);
        handleCancel();
        emits("list");
      }
    })
    .finally(() => {
      loading.value = false;
    });
};

const handleOk = () => {
  loading.value = true;
  const user = JSON.parse(JSON.stringify(formModel));
  user.teacherIds = formModel.teacherIds.join(",");
  if (options.type === 0) {
    delete user.id;
    promise(expertAddApi(user), "新增成功");
  }
  if (options.type === 1) {
    user.teacherIds = ids.value.join(",");
    promise(expertEditApi(user), "修改成功");
  }
};

const show = () => {
  getOptions();
  options.type = 0;
  formModel.groupName = "";
  formModel.teacherIds = "";
  formModel.groupId = "";
  drawer.value?.init();
  loading.value = false;
  formRef.value?.clearValidate();
};

const edit = (data: ExpertGroupUpdateType) => {
  getOptions();
  options.type = 1;
  formModel.groupName = data.groupName;
  formModel.teacherIds = data.teacherIds.split(",");
  formModel.groupId = data.groupId;
  getIds(data.groupId);
  loading.value = false;
  drawer.value?.init();
  formRef.value?.clearValidate();
};

const optionsList = ref<ExpertGroupUpdateType>([]);
const getOptions = () => {
  getTeacherList().then((res) => {
    if (res.code === 200) {
      console.log(res.data)
      optionsList.value = res.data;
    }
  });
};

const ids = ref("");
const names = ref([]);

// 未分组的专家
const getIds = (id: string) => {
  getTeacherIds({ groupId: id }).then((res) => {
    const teacherIds = res.data.teacherIds.split(",");
    const teacherNames = res.data.teacherNames.split(",");
    const citys = res.data.citys.split(",");
    ids.value = teacherIds;
    console.log(res.data)
    names.value = teacherNames.map((name, index) => ({
      id: teacherIds[index],
      name: name,
      city: citys[index]
    }));
  });
};

defineExpose({
  show,
  edit,
});

const mergedOptions = computed(() => {
  return [...names.value, ...optionsList.value];
});
</script>

<template>
  <jin-drawer
    ref="drawer"
    :title="props.title"
    :width="600"
    @ok="handleOk"
    @cancel="handleCancel"
    @beforeOk="handleSubmit"
    :loading="loading"
    :ok-loading="loading"
  >
    <a-form
      auto-label-width
      :model="formModel"
      :rules="rules"
      ref="formRef"
    >
      <a-form-item
        label="专家组名称"
        field="groupName"
      >
        <a-input
          v-model="formModel.groupName"
          allow-clear
          placeholder="请输入专家组名称"
        />
      </a-form-item>

      <!-- 编辑 -->
      <a-form-item
        v-if="options.type === 1"
        label="专家"
        field="teacherIds"
      >
        <!-- <div style="display: flex;">
          <a-checkbox-group v-model="ids">
            <a-checkbox
              v-for="(method,index) in names"
              :key="index"
              :value="method.id"
            >{{method.name}}</a-checkbox>
          </a-checkbox-group>
          <a-checkbox-group v-model="ids">
            <a-checkbox
              v-for="(method,index) in optionsList"
              :key="index"
              :value="method.id"
            >{{method.trueName}}</a-checkbox>
          </a-checkbox-group>
        </div> -->
        <a-checkbox-group v-model="ids">
          <a-checkbox
            v-for="(method, index) in mergedOptions"
            :key="index"
            :value="method.id"
          >
            {{ method.name || method.trueName }}（{{method.city}}）
          </a-checkbox>
        </a-checkbox-group>
      </a-form-item>

      <!-- 新增 -->
      <a-form-item
        v-else
        label="专家"
        field="teacherIds"
      >
        <span
          style="color: #999;"
          v-if="optionsList.length === 0"
        >暂无专家可选</span>
        <div class="grid" v-else>
          <a-checkbox-group
              v-model="formModel.teacherIds"
          >
            <a-checkbox
                v-for="(method,index) in optionsList"
                :key="index"
                :value="method.id"
            >
              {{method.trueName}}（{{method.city}}）
            </a-checkbox>
          </a-checkbox-group>
        </div>
      </a-form-item>

    </a-form>

    <template #footer>
      <a-button>
        关闭
      </a-button>
    </template>
  </jin-drawer>
</template>

<style scoped lang="scss">
:deep(.arco-checkbox-group) {
  display: grid !important;
  width: 100%;
  grid-template-columns: repeat(2, 1fr);
}
</style>